package com.huyucheng.todolist

import android.graphics.Paint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.checkbox.MaterialCheckBox
import com.huyucheng.todolist.utils.executeBackground
import com.huyucheng.todolist.utils.executeMain
import java.sql.ClientInfoStatus
//import com.huyucheng.todolist.TodoListViewModel
import kotlin.concurrent.thread

class TodoAdapter(private val todoListViewModel: TodoListViewModel, private val todoDao: TodoDao,
                  var checkedStatus: Int) : RecyclerView.Adapter<TodoAdapter.ViewHolder>() {

    companion object {
        val TAG: String = "TodoAdapter"
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val todoCheckBox: MaterialCheckBox = view.findViewById(R.id.todo_checkbox)
        val todoContent: TextView = view.findViewById(R.id.todo_content)
        val todoDelete: ImageView = view.findViewById(R.id.delete_todo)
        val todoItem: LinearLayout = view.findViewById(R.id.todo_item)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.todo_item, parent, false)
//        todoDao = AppDatabase.getDatabase(parent.context).todoDao()
        val viewHolder = ViewHolder(view)
        // Checkbox clicked callbacks
        viewHolder.todoCheckBox.setOnClickListener {
            val position = viewHolder.adapterPosition
            val todo = todoListViewModel.getTodo(position, checkedStatus) ?: return@setOnClickListener
            val previousCheckedStatus = todo.checked
            when (todo.checked) {
                TodoListViewModel.CHECKED -> {
                    viewHolder.todoContent.paint.flags = 0 or Paint.ANTI_ALIAS_FLAG
                    viewHolder.todoContent.postInvalidate()
                    todo.checked = TodoListViewModel.UNCHECKED
                }
                TodoListViewModel.UNCHECKED -> {
                    viewHolder.todoContent.paint.flags =
                        Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
                    viewHolder.todoContent.postInvalidate()
                    todo.checked = TodoListViewModel.CHECKED
                }
                else -> {
                    Log.e(TAG, "onCreateViewHolder: failed to check!")
                }
            }
            // update Todo in background
            try {
                executeBackground {
                    todoDao.updateUser(todo)
                }
                todoListViewModel.deleteTodo(todo, previousCheckedStatus)
                todoListViewModel.addTodo(todo, todo.checked)
            } catch (error: Throwable) {
                Log.e(TAG, "onCreateViewHolder: Failed to update database!")
                error.printStackTrace()
                return@setOnClickListener
            }

            val prompt: String  =
                if (todo.checked == TodoListViewModel.CHECKED) {
                    "Checked!"
                } else {
                    "Canceled!"
                }
            Toast.makeText(parent.context, prompt, Toast.LENGTH_SHORT).show()
        }

        // Set delete todo image
        viewHolder.todoDelete.setOnClickListener {
            val position = viewHolder.adapterPosition
            val todo = todoListViewModel.getTodo(position, checkedStatus)!!
            // Coroutine
            try {
                executeBackground {
                    todoDao.deleteTodo(todo)
                }
            } catch (error: Throwable) {
                Log.e(TAG, "onCreateViewHolder: Failed to delete Todo!")
                error.printStackTrace()
                return@setOnClickListener
            }

            todoListViewModel.deleteTodo(todo, checkedStatus)
            Toast.makeText(parent.context, "Delete Successfully!", Toast.LENGTH_SHORT).show()
            notifyDataSetChanged()
        }
        return viewHolder
    }

    override fun getItemCount() = todoListViewModel.getListSize(checkedStatus) ?: 0

    override fun onBindViewHolder(holder: TodoAdapter.ViewHolder, position: Int) {
        val todo: Todo? = todoListViewModel.getTodo(position, checkedStatus)

        val colorInt: Int
        val textColor: Int
        // Set Todo background with color according to priority
        when (todo?.priority) {
            1 -> {
                textColor = holder.todoItem.context.resources.getColor(R.color.colorDimGrey)
                colorInt = holder.todoItem.context.resources.getColor(R.color.priority1)
            }
            2 -> {
                textColor = holder.todoItem.context.resources.getColor(R.color.colorWhite)
                colorInt = holder.todoItem.context.resources.getColor(R.color.priority2)
            }
            3 -> {
                textColor = holder.todoItem.context.resources.getColor(R.color.colorWhite)
                colorInt = holder.todoItem.context.resources.getColor(R.color.priority3)
            }
            else -> {
                textColor = holder.todoItem.context.resources.getColor(R.color.colorDimGrey)
                colorInt = holder.todoItem.context.resources.getColor(R.color.priority0)
            }
        }
        holder.todoItem.setBackgroundColor(colorInt)
        holder.todoContent.setTextColor(textColor)

        // Set checkbox status
        when (todo?.checked) {
            TodoListViewModel.CHECKED -> {
                holder.todoCheckBox.isChecked = true
                holder.todoContent.paint.flags =
                    Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
            }
            TodoListViewModel.UNCHECKED -> {
                holder.todoCheckBox.isChecked = false
                holder.todoContent.paint.flags = 0 or Paint.ANTI_ALIAS_FLAG
            }
            else -> {
                Log.e(TAG, "onBindViewHolder: Test")
            }
        }
        holder.todoContent.text = todo?.content
    }
}